package com.honeywen.mymvc.leetcode;

import java.util.List;

/**
 * 19. 删除链表的倒数第N个节点
 * https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
 *
 * @author wangwei
 * @date 2019/4/22
 */
public class RemoveNthFromEnd {

    static ListNode getNode() {

        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);

        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;

        return node1;


    }

    static void print(ListNode node) {

        while (node != null) {
            System.out.print(node.val + "->");
            node = node.next;
        }
        System.out.println();
    }


    public static ListNode removeNthFromEnd(ListNode head, int n) {

        if (head == null || n <= 0) {
            return null;
        }

        ListNode first = head;
        ListNode second = head;
        for (int i = 0; i < n; i++) {
            second = second.next;

        }

        if (second == null) {
            // 第一个first
            return head.next;
        }

        while (second.next != null) {
            first = first.next;
            second = second.next;
        }
        first.next = first.next.next;

        return head;

    }


    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);

        print(node1);

        print(removeNthFromEnd(node1, 1));

    }


}
